import React, { useState, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import './Qun.css';
import socketService from '../services/socketService';
import { v4 as uuidv4 } from 'uuid';

function Qun() {
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [currentUser, setCurrentUser] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const messagesEndRef = useRef(null);
  const location = useLocation();

  // 从 URL 获取房间 ID
  const getRoomFromPath = () => {
    const path = location.pathname;
    return path.split('/').filter(Boolean).join('-');
  };

  // 初始化 Socket.IO 连接
  useEffect(() => {
    const room = getRoomFromPath();
    // 模拟用户登录
    const user = {
      id: uuidv4(),
      name: '医生',
      role: 'doctor'
    };
    setCurrentUser(user);

    // 连接到服务器
    if (!socketService.isConnected()) {
      socketService.connect();
    }

    // 加入房间
    socketService.joinRoom(user, room);
    setIsConnected(true);

    // 注册消息处理器
    socketService.on('new_message', handleReceiveMessage);
    socketService.on('message_sent', handleMessageSent);
    socketService.on('message_status_update', handleMessageStatusUpdate);

    // 清理函数
    return () => {
      socketService.off('new_message', handleReceiveMessage);
      socketService.off('message_sent', handleMessageSent);
      socketService.off('message_status_update', handleMessageStatusUpdate);
      socketService.leaveRoom();
    };
  }, [location]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleReceiveMessage = (message) => {
    setMessages(prevMessages => {
      // 检查消息是否已存在
      const messageExists = prevMessages.some(msg => msg.id === message.id);
      if (messageExists) {
        return prevMessages;
      }
      // 如果消息不存在，则添加到列表中
      const newMessages = [...prevMessages, message];
      // 标记接收到的消息为已读
      if (message.sender !== currentUser?.id) {
        socketService.markMessagesAsRead([message.id]);
      }
      return newMessages;
    });
  };

  const handleMessageSent = ({ messageId, status }) => {
    setMessages(prevMessages =>
      prevMessages.map(msg =>
        msg.id === messageId ? { ...msg, status } : msg
      )
    );
  };

  const handleMessageStatusUpdate = ({ messageIds, status }) => {
    setMessages(prevMessages =>
      prevMessages.map(msg =>
        messageIds.includes(msg.id) ? { ...msg, status } : msg
      )
    );
  };

  const getCurrentTime = () => {
    const now = new Date();
    return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  };

  const handleSend = () => {
    if (!inputText.trim() || !currentUser || !isConnected) return;

    const newMessage = {
      id: uuidv4(),
      sender: currentUser.id,
      text: inputText,
      time: getCurrentTime(),
      status: 'sending'
    };

    setMessages(prevMessages => [...prevMessages, newMessage]);
    setInputText('');

    // 发送消息到服务器
    socketService.sendMessage(newMessage);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="chat-app">
      <div className="chat-header">
        <h2>李木子</h2>
        <span className={`connection-status ${isConnected ? 'connected' : 'disconnected'}`}>
          {isConnected ? '在线' : '连接中...'}
        </span>
      </div>
      <div className="chat-messages">
        {messages.map((msg) => (
          <div key={msg.id} className={`message ${msg.sender === currentUser?.id ? 'doctor' : 'patient'}`}>
            <div className="message-content">
              <p>{msg.text}</p>
              <div className="message-status">
                {msg.time}
                {msg.sender === currentUser?.id && (
                  <span className="status-icon">
                    {msg.status === 'read' ? ' ✓✓' : ' ✓'}
                  </span>
                )}
              </div>
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      <div className="chat-input">
        <input
          type="text"
          placeholder="输入你想回复的内容"
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyPress={handleKeyPress}
          disabled={!isConnected}
        />
        <button 
          onClick={handleSend}
          disabled={!isConnected || !inputText.trim()}
        >
          发送
        </button>
      </div>
    </div>
  );
}

export default Qun;